package com.spike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spike.config.SMSRabbitConfig;
import com.spike.mapper.BookMapper;
import com.spike.mapper.RecordMapper;
import com.spike.mapper.UserMapper;
import com.spike.model.*;
import com.spike.service.BorrowService;
import com.sun.xml.internal.bind.v2.TODO;
import lombok.AllArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@AllArgsConstructor
@Service
public class BorrowServiceImpl implements BorrowService {
    private final BookMapper bookMapper;
    private final UserMapper userMapper;
    private final RecordMapper recordMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    private static final String BORROW_RECORD_KEY_PREFIX = "borrow_records:user:";
    @Override
    @Transactional
    public Integer borrow(BorrowRecord borrowRecord) {
//        查看是否存在这个用户
        User user = userMapper.selectById(borrowRecord.getUserId());
        if (user != null) {
            //        查看是否有这个书，书里是否有库存
            Book book = bookMapper.selectById(borrowRecord.getBookId());
            if (book.getQuantity()>0&&book != null&&book.getIsDeleted()==1) {
                //        库存减一
                book.setQuantity(book.getQuantity() - 1);
                LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Book::getBookId, book.getBookId());
                bookMapper.update(book, wrapper);
                //        向借阅记录表插入一条借阅记录
                LocalDate localDate = LocalDate.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String formattedDate = localDate.format(formatter);
                java.util.Date utilDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
                borrowRecord.setBorrowDate(utilDate);
                recordMapper.add(borrowRecord);
                SMS sms = new SMS();
                sms.setUserId(user.getUserId());
                sms.setPhone(user.getPhoneNumber());
                sms.setBookTitle(book.getTitle());
                sms.setBorrowDate(borrowRecord.getBorrowDate());
                rabbitTemplate.convertAndSend(SMSRabbitConfig.EXCHANGE_NAME,"phone",sms.toString());
                return borrowRecord.getRecordId();
            }
        }
        return null;
    }
@Transactional
    @Override
    public Boolean retuenBook(BorrowRecord borrowRecord) {
        BorrowRecord borrowRecord1 = recordMapper.selectById(borrowRecord.getRecordId());
        if (borrowRecord1 != null) {
//            库存加一
            Book book = bookMapper.selectById(borrowRecord1.getBookId());
            book.setQuantity(book.getQuantity() + 1);
            bookMapper.update(book, new LambdaQueryWrapper<Book>().eq(Book::getBookId, borrowRecord1.getBookId()));
//            修改借阅记录里面的归还时间
            LocalDate localDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = localDate.format(formatter);
            java.util.Date utilDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            borrowRecord.setReturnDate(utilDate);
            recordMapper.update(borrowRecord, new LambdaQueryWrapper<BorrowRecord>().eq(BorrowRecord::getRecordId, borrowRecord.getRecordId()));
        return true;
        }
        return false;
    }

    @Override
    public List<BorrowRecordSummary> findListByUserId(Integer userId) {
        String key = BORROW_RECORD_KEY_PREFIX + userId;
//        根据key去redis里面查询
        List<BorrowRecordSummary> redislist = (List<BorrowRecordSummary>) redisTemplate.opsForValue().get(key);
        if (redislist != null) {
            return redislist;
        }
//        redis不存在
        ArrayList<BorrowRecordSummary> list = new ArrayList<>();
        for (BorrowRecord borrowRecord : recordMapper.selectList(new LambdaQueryWrapper<BorrowRecord>().eq(BorrowRecord::getUserId, userId))) {
            BorrowRecordSummary summary = new BorrowRecordSummary();
            summary.setRecordId(borrowRecord.getRecordId());
            summary.setBookTitle(bookMapper.selectById(borrowRecord.getBookId()).getTitle());
            summary.setBorrowDate(borrowRecord.getBorrowDate());
            summary.setReturnDate(borrowRecord.getReturnDate());
            list.add(summary);
        }
//        将结果保存到redis里面
        redisTemplate.opsForValue().set(key, list,1, TimeUnit.HOURS);
        return list;
    }
}
